<template>
	<view class="live-container">
		<!-- 左侧区域：直播标题和画面 -->
		<view class="left-container">
			<!-- 直播标题区域 -->
			<view class="live-title">
				<view class="back-btn" @click="goBack">
					<uni-icons type="left" size="24" color="#ffffff"></uni-icons>
				</view>
				<view class="title-content">
					<text class="title-text">逃出五角大楼职业联赛官方直播间-成都AG VS 武汉EDG</text>
					<view class="live-status">
						<view class="live-dot"></view>
						<text class="live-text">直播中</text>
					</view>
				</view>
				<view class="share-btn">
					<uni-icons type="share" size="24" color="#ffffff"></uni-icons>
				</view>
			</view>

			<!-- 直播画面区域 -->
			<view class="live-player-container">
				<!-- 使用第三方播放器容器 -->
				<view id="videoContainer" class="live-player"></view>
				<!-- 观看人数 -->
				<view class="view-count">
					<uni-icons type="eye" size="14" color="#ffffff"></uni-icons>
					<text class="count-text">{{viewCount}}</text>
				</view>
			</view>

			<!-- 礼物区域 -->
			<view class="gift-area">
				<view class="gift-title">热门礼物</view>
				<view class="gift-list">
					<view v-for="(gift, index) in gifts" :key="index" class="gift-item"
						:class="{ 'active': selectedGiftIndex === index }" @click="selectGift(index)">
						<image :src="gift.img" mode="aspectFit" class="gift-image"></image>
						<text class="gift-name">{{gift.name}}</text>
						<text class="gift-price">{{gift.money}}金币</text>
					</view>
				</view>
				<view class="give-btn1" style="float: left;width: 200px;">
					<text>余额：{{userGold}}</text>
				</view>
				<view class="give-btn" style="float: left;margin-left: 5px;" @click="giveGift">
					<text>赠送</text>
				</view>
			</view>
		</view>

		<!-- 右侧区域：聊天信息 -->
		<view class="right-container">

			<!-- 排行榜区域 -->
			<view class="gift-ranking">

				<view class="ranking-item">
					<view class="ra-name" style="color: #4d4d4d;font-size: 12px;">7天内送礼，发言等可上榜</view>
					<view class="ra-money" style="color: #4d4d4d;">互动值</view>
				</view>
				<view class="ranking-item" v-for="(item,index) in rankingItem">
					<image v-if="index == 0" class="ra-img"
						src="">
					</image>
					<image v-else-if="index == 1" class="ra-img"
						src="">
					</image>
					<image v-else-if="index == 2" class="ra-img"
						src="">
					</image>
					<view v-else class="ra-img-1">
						{{ index + 1 }}
					</view>
					<view class="ra-name">
						<view style="width: 20%;float: left;">Lv{{item.level}}</view>
						<view style="width: 80%;float: left;">{{item.nickname}}</view>
					</view>
					<view class="ra-money">{{item.contribution}}</view>
				</view>
			</view>

			<!-- 礼物动画区域 -->
			<view class="gift-animation-area" v-for="(item,index) in giftShow"
				:style="{ top: (260 + (index + 1) * 60) + 'px' }">
				<view class="my-gift">
					<view class="gift-username" style="color: #fff;">张三 送：</view>
					<view class="gift-gift">
						<Gift
							imageUrl="https://huyaimg.msstatic.com/cdnimage/actprop/20699_1_0_prop_streamer_resource_1639991857.png"
							:frameCount="10" :duration="1.5" :width="60" :height="60"></Gift>
					</view>
				</view>
			</view>
			<!-- 导入组件 -->
			<LiveChat :date="chatMessages" ref="liveChatRef"></LiveChat>
		</view>

	</view>
</template>

<script>
	import {
		selectGift,
		getUserGold,
		giveGift,
		getUserByContribution,
		getGiftInfoById
	} from "@/api/live";
	import LiveChat from "@/component/LiveChat.vue";
	import Gift from "@/component/gift/Gift.vue";
	import {
		h,
		getCurrentInstance
	} from 'vue';


	export default {
		data() {
			return {
				liveUrl: 'http://192.168.1.9:7788/live/666/hls.m3u8',
				viewCount: '1.2万',
				chatMessages: [{}, {}, {}, {}, {}, {}, {}],
				gifts: [

				],
				rankingItem: [],
				selectedGiftIndex: -1,
				animationQueue: [],
				clientObj: client,
				userGold: 0,
				giftShow:[
						  {},{},{},{},{},{}
					  ]
			}
		},
		components: {
			LiveChat,
			Gift
		},
		mounted() {
			// 初始化第三方播放器
			this.initPlayer();

			//获取礼物列表
			this.getGift();

			//获取用户金币
			this.getUserMoney();

			this.getMsg();

			//获取排行榜
			this.getContribution();
		},
		beforeDestroy() {
			// 销毁播放器
			if (this.player) {
				this.player.dispose();
			}
		},
		methods: {
			getContribution() {
				getUserByContribution().then((data) => {
					console.log("排行榜", data);
					this.rankingItem = data.data.records;
				});
			},
			getMsg(){
					console.log("订阅")
					// 订阅消息
					this.clientObj.subscribe("/wujiao/live", (msg) => {
					  let json = JSON.parse(msg.body);
					  console.log(111,json.code);
					  if(json.code == 0){//消息
						  this.chatMessages.push(json);
						  this.$refs.liveChatRef.getScoll();
					  }else if(json.code == 1){//礼物
					      let giftId = json.giftId;
						  //获取礼物的详细信息
						  console.log(111,giftId)
						  getGiftInfoById(giftId).then((data)=>{
							  console.log(2222);
							  console.log("礼物详细信息",data);
							  json.imgRun = data.data.imgRun;
							  //添加消息
							  this.chatMessages.push(json);
							  this.$refs.liveChatRef.getScoll();
						  })
							
						  
						  //播放礼物动画
						  
						  
						  //获取排行榜
						  this.getContribution();
						  //获取礼物列表
						  this.getGift();
					  }
					  
					    // 检查消息数量是否超过50
					    if (this.chatMessages.length > 50) {
					      // 移除最上面（最早）的消息，保持列表最多50条
					      this.chatMessages.shift();
					    }
			
					   
					  console.log("111", json);
					});
				},
			getUserMoney() {
				getUserGold().then((data) => {
					this.userGold = data.data;
				});
			},
			getGift() {
				selectGift().then((data) => {
					console.log("礼物", data);
					this.gifts = data.data;
				});
			},
			initPlayer() {
				// 确保第三方播放器库已加载
				if (typeof Hls !== 'undefined') {
					const videoContainer = document.getElementById('videoContainer');
					if (videoContainer) {
						// 创建video元素
						const videoElement = document.createElement('video');
						videoElement.id = 'livePlayer';
						videoElement.className = 'live-player';
						videoElement.autoplay = true;
						videoElement.controls = true;
						videoElement.style.width = '100%';
						videoElement.style.height = '100%';

						videoContainer.appendChild(videoElement);

						// 初始化HLS播放器
						if (Hls.isSupported()) {
							this.player = new Hls();
							this.player.loadSource(this.liveUrl);
							this.player.attachMedia(videoElement);
							this.player.on(Hls.Events.MANIFEST_PARSED, () => {
								console.log('HLS播放器初始化成功');
							});
							this.player.on(Hls.Events.ERROR, (event, data) => {
								console.error('HLS播放器错误:', data);
								this.videoErrorCallback(data);
							});
						}
						// 浏览器原生支持HLS
						else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
							videoElement.src = this.liveUrl;
							videoElement.addEventListener('loadedmetadata', () => {
								videoElement.play();
							});
							videoElement.addEventListener('error', (e) => {
								this.videoErrorCallback(e);
							});
						} else {
							console.error('当前浏览器不支持HLS播放');
							uni.showToast({
								title: '当前浏览器不支持直播播放',
								icon: 'none'
							});
						}
					}
				} else {
					console.error('HLS库未加载，请确保在index.html中引入了HLS.js');
					uni.showToast({
						title: '直播播放器加载失败',
						icon: 'none'
					});
				}
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			videoErrorCallback(e) {
				console.error('视频播放出错：', e);
				uni.showToast({
					title: '直播连接失败，请稍后重试',
					icon: 'none'
				});
			},
			selectGift(index) {
				this.selectedGiftIndex = index;
			},
			giveGift() {
				if (this.selectedGiftIndex === -1) {
					uni.showToast({
						title: '请选择礼物',
						icon: 'none'
					});
					return;
				}

				// 发请求来判断金币
				const selectedGift = this.gifts[this.selectedGiftIndex];

				console.log("当前选择的礼物", selectedGift);
				console.log("当前选择的礼物2", this.userGold);

				if (this.userGold < selectedGift.money) {
					uni.showToast({
						title: '金币不足',
						icon: 'none'
					});
					return;
				}

				// 扣除金币 - 后台接口
				giveGift(selectedGift.id).then((data) => {
					console.log("结果", data);
					if (data.code == 200) {
						let info = uni.getStorageSync("userInfo");
						//广播一下

						const json = {
							code: 1, //弹幕信息
							nickname: info.nickname,
							level: info.level,
							avatar: info.avatar,
							content: selectedGift.name + " x1",
							giftId: selectedGift.id
						};
						console.log("12345678889", json)
						client.send("/app/live", {}, JSON.stringify(json))
					} else {
						uni.showToast({
							title: data.msg,
							icon: 'none'
						});
					}
					this.getUserMoney();
				})

			},
			addGiftAnimation(gift) {

			}
		}
	}
</script>

<style lang="scss" scoped>
	// 导入字体图标
	@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

	.right-container {
		position: relative;
		width: 20%;
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #1a1a1a;
		border-left: 1px solid #333333;
	}

	.live-container {
		width: 100%;
		height: 100vh;
		display: flex;
		background-color: #000000;
		position: relative;
	}

	.left-container {
		width: 79%;
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.live-title {
		height: 8vh;
		width: 95%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}

	.back-btn,
	.share-btn {
		width: 30px;
		height: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.title-content {
		display: flex;
		align-items: center;
	}

	.title-text {
		color: #ffffff;
		font-size: 16px;
		margin-right: 10px;
	}

	.live-status {
		display: flex;
		align-items: center;
	}

	.live-dot {
		width: 8px;
		height: 8px;
		background-color: #ff0000;
		border-radius: 50%;
		margin-right: 5px;
		animation: pulse 1.5s infinite;
	}

	@keyframes pulse {
		0% {
			transform: scale(0.95);
			box-shadow: 0 0 0 0 rgba(255, 0, 0, 0.7);
		}

		70% {
			transform: scale(1);
			box-shadow: 0 0 0 6px rgba(255, 0, 0, 0);
		}

		100% {
			transform: scale(0.95);
			box-shadow: 0 0 0 0 rgba(255, 0, 0, 0);
		}
	}

	.live-text {
		color: #ff0000;
		font-size: 12px;
	}

	.live-player-container {
		height: 100vh;
		flex: 1;
		width: 100%;
		z-index: 999;
		position: relative;
	}

	.live-player {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.view-count {
		position: absolute;
		bottom: 10px;
		right: 10px;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 15px;
		padding: 3px 10px;
		display: flex;
		align-items: center;
	}

	.count-text {
		color: #ffffff;
		font-size: 12px;
		margin-left: 5px;
	}

	.gift-area {
		height: 20vh;
		width: 100%;
		background-color: rgba(0, 0, 0, 0.7);
		padding: 5px;
	}

	.gift-title {
		color: #ffffff;
		font-size: 12px;
		margin-bottom: 10px;
	}

	.gift-list {
		width: 100%;
		display: flex;
		margin-bottom: 10px;
	}

	.gift-item {
		width: 60px;
		height: 80px;
		margin-right: 10px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 10px;
		background-color: rgba(255, 255, 255, 0.1);
		cursor: pointer;
	}

	.gift-item.active {
		background-color: rgba(255, 153, 0, 0.3);
	}

	.gift-image {
		width: 40px;
		height: 40px;
		margin-bottom: 5px;
	}

	.gift-name {
		color: #ffffff;
		font-size: 12px;
		margin-bottom: 2px;
	}

	.gift-price {
		color: #ff9900;
		font-size: 10px;
	}

	.give-btn {
		height: 30px;
		width: 80px;
		background-color: #ff9900;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
		font-size: 14px;
		cursor: pointer;
	}

	.give-btn1 {
		height: 30px;
		width: 80px;
		background-color: #ff270b;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
		font-size: 14px;
		cursor: pointer;
	}



	.give-btn1 {
		height: 30px;
		width: 80px;
		background-color: #ff270b;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
		font-size: 14px;
		cursor: pointer;
	}

	.chat-container {
		flex: 1;
		padding: 10px;
		overflow: hidden;
	}

	.gift-animation-area {
		position: absolute;
		left: 0px;
		width: 100%;
		height: 60px;
		z-index: 88;
		background-image: url("/static/gift-bg.png");
		background-size: 100% 100%;
		animation: gift-animation 4s forwards cubic-bezier(0.25, 0.1, 0.25, 1);
	}

	.user-avatar {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		margin-right: 8px;
	}

	.user-name {
		color: #ff9900;
		font-size: 14px;
		font-weight: bold;
	}

	.input-area {
		height: 50px;
		width: 100%;
		display: flex;
		align-items: center;
		padding: 0 10px;
		background-color: #222222;
		border-top: 1px solid #333333;
	}

	.input-wrapper {
		flex: 1;
		height: 30px;
		margin-right: 10px;
		background-color: #333333;
		border-radius: 15px;
		padding: 0 10px;
		display: flex;
		align-items: center;
	}

	.chat-input {
		flex: 1;
		height: 100%;
		color: #ffffff;
		font-size: 14px;
	}

	.send-btn {
		width: 60px;
		height: 30px;
		background-color: #ff9900;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
		font-size: 14px;
	}


	.my-gift {
		width: 100%;
		height: 80px;
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		margin: auto 0;
		background-image: url("/static/gift-bg.png");
		background-repeat: no-repeat;
		background-position: center;
	}

	@keyframes gift-animation {
		0% {
			left: 100%;
			opacity: 0;
			transform: scale(0.9);
		}

		/* 从右侧外开始，轻微缩小 */
		25% {
			left: 10px;
			opacity: 1;
			transform: scale(1);
		}

		/* 缓慢进入，25%时间完成（之前是50%） */
		85% {
			left: 10px;
			opacity: 1;
			transform: scale(1);
		}

		/* 延长显示时间到85% */
		100% {
			left: -300px;
			opacity: 0;
			transform: scale(0.9);
		}

		/* 快速退出，最后15%时间完成 */
	}

	.gift-username {
		width: 40%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		float: left;
	}

	.gift-gift {
		width: 60%;
		float: left;
		text-align: right;
	}

	.gift-img {
		float: left;
		line-height: 60px;
	}


	.gift-animation-item {
		height: 50px;
		width: 300px;
		background-color: rgba(0, 0, 0, 0.7);
		border-radius: 25px;
		margin-bottom: 10px;
		display: flex;
		align-items: center;
		padding: 0 15px;
		opacity: 0;
		transform: translateX(-100%);
		transition: all 0.5s ease;
	}

	.gift-animation-item.slide-in {
		opacity: 1;
		transform: translateX(0);
	}

	.gift-animation-item.fade-out {
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.gift-animation-content {
		display: flex;
		align-items: center;
		width: 100%;
	}

	.gift-animation-item .user-avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.animation-text {
		flex: 1;
		display: flex;
		flex-direction: column;
		color: #fff;
	}

	.gift-animation-item .user-name {
		color: #ffffff;
		font-size: 14px;
		font-weight: bold;
	}

	.gift-animation-item .gift-name {
		color: #ff9900;
		font-size: 14px;
	}

	.gift-animation-item .gift-image {
		width: 40px;
		height: 40px;
	}

	.gift-ranking {
		position: absolute;
		top: 0;
		width: 100%;
		height: 30vh;
		z-index: 998;
		background-color: rgba(255, 255, 255, 0.9);
		overflow-y: auto;

		scrollbar-width: none;
		/* Firefox */
		-ms-overflow-style: none;
		/* IE 10+ */
	}

	.ranking-item {
		width: 90%;
		padding: 0 5%;
		height: 20px;
		line-height: 20px;
		display: flex;
		margin-top: 3px;
	}

	.ra-name {
		width: 60%;
	}

	.ra-money {
		width: 40%;
		text-align: right;
	}

	.ra-img {
		width: 20px;
		height: 20px;
		margin-top: 0px;
		margin-right: 5px;
	}

	.ra-img-1 {
		width: 16px;
		height: 16px;
		margin-top: 2px;
		margin-left: 2px;
		margin-right: 8px;
		background-image: url("");
		background-size: 100% 100%;
		text-align: center;
		line-height: 16px;
		font-size: 8px;
		color: #fff;
	}
</style>